﻿using RimWorld;
using Verse;
using System;
using System.Linq;
using Verse.Noise;
using static System.Collections.Specialized.BitVector32;

namespace RimZombieGirl
{
    public class IncidentWorker_DaoTravelPriestJoin : IncidentWorker_GiveDaoFriendlyBase
    {
        public virtual bool CanSpawnJoiner(Map map)
        {
            return TryFindEntryCell(map, out _);
        }

        public virtual Pawn GeneratePawn(Map map)
        {
            Gender? gender = null;
            if (this.def.pawnFixedGender != Gender.None)
                gender = this.def.pawnFixedGender;

            Ideo ideo = null;
            if (ModsConfig.IdeologyActive)
            {
                var candidateIdeos = Find.IdeoManager.IdeosListForReading
                    .Where(i => !Faction.OfPlayer.ideos.Has(i))
                    .ToList();

                candidateIdeos.TryRandomElementByWeight(i => IdeoUtility.IdeoChangeToWeight(null, i), out ideo);
            }

            // 道士种类
            PawnKindDef priestKind = DefDatabase<PawnKindDef>.GetNamedSilentFail("RI_DaoPawn_TravelPriest");
            if (priestKind == null)
            {
                Log.Error("无法找到 PawnKindDef: RI_DaoPawn_TravelPriest");
                return null;
            }
            Pawn priest = PawnGenerator.GeneratePawn(new PawnGenerationRequest(
                priestKind,
                Find.FactionManager.FirstFactionOfDef(FactionDef.Named("RI_Faction_Dao")),
                PawnGenerationContext.NonPlayer,
                map.Tile,
                forceGenerateNewPawn: true));


            // 尝试生成在殖民地附近
            IntVec3 spawnCell = CellFinder.RandomClosewalkCellNear(map.Center, map, 5);
            GenSpawn.Spawn(priest, spawnCell, map);

            // 触发“入伙意愿”
            priest.guest.SetGuestStatus(Faction.OfPlayer, GuestStatus.Guest);
            priest.mindState.WillJoinColonyIfRescued = true;
            return priest;
        }

        protected override bool ExecuteFriendlyEvent(IncidentParms parms, Map map, Faction daoFaction)
        {
            if (!CanSpawnJoiner(map))
                return false;

            Pawn priest = GeneratePawn(map);
            if (priest == null)
                return false;


            TaggedString letterText = "RI_DaoTravelPriestJoin.letterText".Translate(priest.Named("PAWN"));
            TaggedString letterLabel = "RI_DaoTravelPriestJoin.letterLabel".Translate(priest.Named("PAWN"));

            PawnRelationUtility.TryAppendRelationsWithColonistsInfo(ref letterText, ref letterLabel, priest);

            base.SendStandardLetter(letterLabel, letterText, LetterDefOf.PositiveEvent, parms, priest, Array.Empty<NamedArgument>());

            return true;
        }

        protected bool TryFindEntryCell(Map map, out IntVec3 cell)
        {
            return CellFinder.TryFindRandomEdgeCellWith(c => map.reachability.CanReachColony(c) && !c.Fogged(map),
                map, CellFinder.EdgeRoadChance_Neutral, out cell);
        }
    }
}
